<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Grid\User\UserMigration;
use App\Admin\Actions\Tools\User\CreateAgent;
use App\Admin\Actions\Grid\User\FreezeBalance;
use App\Admin\Actions\Grid\User\UserSignGrid;
use App\Admin\Actions\Grid\User\AssetUpdate;
use App\Admin\Repositories\User;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class UserController extends AdminBaseController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new User(['assets']), function (Grid $grid) {
            $grid->model()->orderByDesc('id');
            $this->gridFilter($grid, 'users', true);
            $grid->column('id')->sortable();

            $grid->column("back_type", "类型")->display(function () {
                if ($this->admin_id > 0) {
                    return "代理";
                } else {
                    return "用户";
                }
            })->label();
//            $grid->column('name');

            $grid->column('rid')->display(function ($rid) {
                return $rid && $this->referer ? $this->referer->username : "-";
            });

            $grid->column('email');
            $grid->column('nickname')->editable();
//            $grid->column('avatar');
//            $grid->column('phone');
//            $grid->column('email_verified_at');
//            $grid->column('password');
//            $grid->column('pay_password');

//            $grid->column('google_captcha');
//            $grid->column('google_captcha_new');
//            $grid->column('google_captcha_check');
            $grid->column('invite_code')->copyable();
            $grid->column('is_sign')->using(tt_status_yes_no('', true))->label([
                STATUS_NO => 'default',
                STATUS_YES => 'info'
            ])->help("只有用户有提交申请才可以签约");
//            $grid->column('sign_status', __("签约申请"));
            $grid->column('sign_status', __("签约申请"))->using(tt_user_sign_status('', true))->label([
                USER_SIGN_STATUS => 'default',
                USER_SIGN_STATUS_COMMIT => 'info',
                USER_SIGN_STATUS_SUCCESS => 'success'
            ]);

            $grid->column('risk')->using(tt_risk_status('', true))->label([
                RISK_STATUS_WIN => 'success',
                RISK_STATUS_LOSS => 'danger',
                RISK_STATUS_NONE => 'default'
            ]);
            $grid->column('assets.balance', __('可用余额'))->numberFormat();
//            $grid->column('register_type');
//            $grid->column('area_id');
            $grid->column('ip', __("最后访问IP"));

            $grid->column('created_at', __("注册时间"));
            $grid->column('status')->switch();

            $grid->disableViewButton();
//            $grid->disableEditButton();

            $grid->disableCreateButton();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->append(new AssetUpdate());
                $actions->append(new FreezeBalance());
                if ($this->trade_status == USER_SIGN_STATUS_COMMIT && $this->is_sign == STATUS_NO) {
                    $sign_grid = new UserSignGrid();
                    $sign_grid->setInput(['status' => USER_SIGN_STATUS_SUCCESS]);
                    $actions->append($sign_grid);
                }

                if (Admin::user()->isAdministrator()) {
                    $actions->append(new UserMigration());
                }
            });

            $grid->tools(new CreateAgent());

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id')->width(3);
                $filter->like('name')->width(3);
                $filter->equal('phone')->width(3);
                $filter->equal('email')->width(3);
                $filter->between('created_at')->datetime()->width(6);

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new User(), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('nickname');
            $show->field('avatar')->image(g_admin_image());
            $show->field('email');
            $show->field('phone');
            $show->field('email_verified_at');
            $show->field('password');
            $show->field('pay_password');
            $show->field('rid');
            $show->field('google_captcha');
            $show->field('google_captcha_new');
            $show->field('google_captcha_check');
            $show->field('status')->as(function ($status) {
                return $status == 1 ? '启用' : '禁用';
            });
            $show->field('ip');
            $show->field('invite_code');
            $show->field('register_type');
            $show->field('area_id');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new User(), function (Form $form) {
            $form->display('id');
            $form->text('name')->readOnly();
            $form->text('nickname');

            $form->password('password', __('登录密码'))->required()->rules('required|min:6', [
                'min' => '密码不能少于6个字符',
            ]);

            $form->password('pay_password', __('提现密码'))->rules('max:32', [
                'max' => '密码不能少于32个字符',
            ]);
//            $form->image('avatar')->removable();
//            $form->email('email');
//            $form->text('phone');
//            $form->password('password');
//            $form->password('pay_password');
//            $form->text('rid');
//            $form->text('google_captcha');
//            $form->text('google_captcha_new');
//            $form->text('google_captcha_check');
            $form->switch('status');
            $form->select('risk')->options(tt_risk_status('', true))->default(RISK_STATUS_NONE)->required();
//            $form->text('ip');
//            $form->text('invite_code');
//            $form->select('register_type')->options(AuthType::$lib_register_type)->required();
//            $form->text('area_id');
//            $form->display('email_verified_at');
            $form->display('created_at');
            $form->display('updated_at');

            $form->saving(function (Form $form) {
                if (Hash::needsRehash($form->password)) {
                    $form->password = Hash::make($form->password);
                } else {
                    unset($form->password);
                }

                if ($form->pay_password) {
                    if (Hash::needsRehash($form->pay_password)) {
                        $form->pay_password = Hash::make($form->pay_password);
                    } else {
                        unset($form->pay_password);
                    }
                }

            });
        });
    }

    public function search(Request $request)
    {
        $q = $request->input('q');
        $result = \App\Models\User::query()->where('email', 'like', "%$q%")
            ->where('admin_id', ">", 0)->paginate(null, ['id', 'email']);
        if ($result) {
            $result = json_decode(json_encode($result), true);
        }
        foreach ($result['data'] as $k => &$v) {
            $v['text'] = $v['email'] . "(" . $v['id'] . ")";
        }
        return response()->json($result);
    }
}
